window.onload = function () {

	var str = "";
	var res = "";
	var resdisplay = document.getElementsByClassName('resdisplay');
	var showhistory = document.getElementsByClassName('cal-title')[0];
	var calHistroy = document.getElementsByClassName('cal-histroy');
	var l = document.getElementsByClassName('num-button');
	for (let i = 0; i < l.length; i++) {
		l[i].onclick = function () {

			var sStr = this.innerHTML 
			
			if (sStr == "=") {
				sStr = result(str); 
				
				if (document.getElementsByClassName('cal-result')[1].innerHTML == "there is no history yet") {
					document.getElementsByClassName('cal-result')[1].innerHTML = '';
				}
				if (sStr == "格式错误" || sStr == undefined) {
					sStr = "格式错误";
					resdisplay[0].innerHTML = "<span class='cal-exp'>" + str + "</span> <br><span style='font-size:22px;color:red;'>" + sStr + "</span>";
					calHistroy[0].innerHTML += '<div class="historyResult"><span class="cal-exp">' + str + '</span> <br><span style="font-size:22px;color:red;">' + sStr + '</span><br> <br></div>';
					sStr = "";
					str = "";
				} else {
					resdisplay[0].innerHTML = '<span class="cal-exp">' + str + '</span><br> <span class="cal-result">' + sStr + '</span><br>';
					calHistroy[0].innerHTML += '<div class="historyResult" onclick="historyResult(event)"><span class="cal-exp">' + str + '</span><br> <span class="cal-result">' + sStr + '</span><br> <br></div>';
					str = sStr;
					sStr = "";
				}
				str = "";
			} else if (sStr == "←") {
				sStr = "";
				str = BK(str); 
				resdisplay[0].innerHTML = "<span class='cal-exp'>" + str + "</span> <br><span class='cal-result'>" + sStr + "</span>"
			} else if (sStr == "C") {
				str = "";
				sStr = "";
				resdisplay[0].innerHTML = "<span class='cal-result' style='color:#000;font-size: 24px;'>0</span>"  
			} else if (sStr == "CE") { 
				str = "";
				sStr = "";
				resdisplay[0].innerHTML = "<span class='cal-result' style='color:#000;font-size: 24px;'>0</span>"
				calHistroy[0].innerHTML = "<span class='cal-result' style='color:#aaa;'>there is no history yet</span>"
			} else if (sStr == "√") {
				if (str) {
					sStr = Math.sqrt(str);
				} else {
					sStr = "格式错误";
				}
				formatDisplay(str,sStr)
				str = '';
			} else if (sStr == "x<sup>2</sup>") {
				if (str) {
					sStr = val(str + "*" + str);
				} else {
					sStr = "格式错误";
				}
				formatDisplay(str,sStr)
				str = '';
			} else if (sStr == "<sup>1</sup>/<sub>x</sub>") {
				sStr = val("1/" + str);
				formatDisplay(str,sStr)
				str = '';
			} else {
				str += this.innerHTML;

				resdisplay[0].innerHTML = "<span class='cal-exp'>" + str + "</span> <br><span class='cal-result'>" + sStr + "</span>"
			}
		}
	} 
	resdisplay[0].onclick = function() { 
		if (window.innerWidth < 530) {
			calHistroy[0].style.cssText = "display:none";
		}
	}
	function formatDisplay(str, sStr) {
		if (document.getElementsByClassName('cal-result')[1].innerHTML == "there is no history yet") {
			document.getElementsByClassName('cal-result')[1].innerHTML = '';
		}
		calHistroy[0].innerHTML += '<div class="historyResult" onclick="historyResult(event)"><span class="cal-exp">' + str + '</span><br> <span class="cal-result">' + sStr + '</span><br> <br></div>';
		resdisplay[0].innerHTML = "<span class='cal-exp'>" + str + "</span> <br><span class='cal-result'>" + sStr + "</span>"
	}
	function BK(v) {
		if (v.length >= 1) {
			return v.substring(0, v.length - 1);
		} else {
			return '';
		}
	}
	function result(str) {
		try { 
			return val(str);
		}
		catch (exception) {
			return "格式错误";
		}
	}

	showhistory.onclick = function () {
		if (document.getElementsByClassName('cal-histroy')[0].style.cssText == "") {
			document.getElementsByClassName('cal-histroy')[0].style.cssText = "display:none";
		} else {
			document.getElementsByClassName('cal-histroy')[0].style.cssText = "";
		}
	}

	myResize(); // 页面第一次加载时，判断窗口的宽度来决定history的显示方式

	// 监听窗口大小来控制history的显示
	window.addEventListener('resize', function () {
		myResize();
	});

	function myResize() {
		if (window.innerWidth > 530) {
			document.getElementsByClassName('cal-histroy')[0].style.cssText = "";
		} else {
			document.getElementsByClassName('cal-histroy')[0].style.cssText = "display:none";
		}
	}
	// val('2*12/(3*(5-1))'); // test
	val('(9-3)*2'); // test
	function val(s) { // 计算式子，s为表达式 
		var c = s.split(''); 
		var tmp = '', arr = [];
		for(let i = 0;i<c.length;i++){  
			if (!isNaN(parseFloat(c[i])) || c[i] == '.') {
				tmp=""+tmp + c[i]; 
				if (isNaN(parseFloat(c[i+1])) && c[i+1] != '.') {
					arr.push(tmp);
					tmp = '';
				}
			}
			if (isNaN(parseFloat(c[i])) && c[i] != '.') { 
				arr.push(c[i]);
			} 
		}    
		arr = priorityBrackets(arr,0,arr.length); // 优先计算小括号内的
		// arr = bbb(["-10", "/", "(", "5", "-", "1", ")"]  ,0,7); //test
		arr = compute(arr,0,arr.length); 
		console.log(arr);
		
		return arr[0]==" "&&arr[0] != 0?arr[1]:isNaN(arr[0])?'格式错误':arr[0];
	} 


	// 优先计算括号里面的表达式
	function priorityBrackets (arr,start, end) {
		for (let i = start; i<end;i++) {
			if (arr[i] == "(") {
				for (let j = i+1; j<end;j++) {
					if (arr[j] == "(") {
						i = j-1;
						break;
					} else if (arr[j] == ")"){
						let a = []; 
						for (let k = i+1; k<j; k++) {
							a.push(arr[k]);
						} 
						arr.splice(i,a.length+2);  
						arr.splice(i, 0, compute(a,0,a.length).toString()); 
						i=0;
						break;
					}
				}
			}
		} 
		return arr;
	}

	// 计算单纯的表达式，即没有括号的
	 function compute (arr, start, end) {
		 
		let l = arr.length;
		for (let i = start; i< end; i++) {
			if (arr[i] == '%' ) {   
				if (isRight(arr[i+1])) {
					return "格式错误";
				}
				let n1 = parseFloat(arr[i-1]); 
				let n2 = parseFloat(arr[i+1]); 
				let sum = n1%n2;
				arr.splice(i-1,3)
				arr.splice(i-1, 0, sum);   
				i = 0;
			}
			if (arr[i] == '/' ) {   
				if (isRight(arr[i+1])) {
					return "格式错误";
				}
				
				let n1 = parseFloat(arr[i-1]); 
				let n2 = parseFloat(arr[i+1]); 
				let sum = n1/n2;
				arr.splice(i-1,3)
				arr.splice(i-1, 0, sum);   
				i = 0;
			} 
			if (arr[i] == '*') {   
				if (isRight(arr[i+1])) {
					return "格式错误";
				}
				let n1 = parseFloat(arr[i-1]); 
				let n2 = parseFloat(arr[i+1]); 
				let sum = n1*n2;
				arr.splice(i-1,3)
				arr.splice(i-1, 0, sum);   
				i = 0;
			}
		}   
		for (let i = start; i< end; i++) {    
			if (arr[i] == '+' ) { 
				if (isRight(arr[i+1])) {
					return "格式错误";
				}
				let n1 = parseFloat(arr[i-1]); 
				let n2 = parseFloat(arr[i+1]); 
				let sum = n1+n2;
				arr.splice(i-1,3)
				arr.splice(i-1, 0, sum);   
				i = 0;
			}
			if (arr[i] == '-') {
				if (isRight(arr[i+1])) {
					return "格式错误";
				}
				let n1 = parseFloat(arr[i-1]); 
				let n2 = parseFloat(arr[i+1]); 
				let sum = n1-n2;
				arr.splice(i-1,3)
				arr.splice(i-1, 0, sum);  
				i = 0;
			} 
		} 
		return arr;
	 }
	function isRight(n) {
		if (n == '/' || n == '*' || n == '+' || n == '-' || n == '%' || n == '(' || n == ')') {
			return true;
		} else {
			return false;
		}
	}
}
function historyResult (e) {
	document.getElementsByClassName('resdisplay')[0].innerHTML = e.srcElement.innerHTML.substring(0,e.srcElement.innerHTML.length-5); 
}